package com.example.apidocserver.infrastructure.util.word;

import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;

import static com.example.apidocserver.infrastructure.util.word.WordConstants.*;

/**
 * 文档生成段落工具
 *
 * @author xyqlg
 */
public class WordParagraphUtil {
    private final static int[] TITLE_FONT_SIZES = {H1_SIZE, H2_SIZE, H3_SIZE, H4_SIZE, H5_SIZE};

    /**
     * 设置为标题
     * titleRun.setUnderline(UnderlinePatterns.SINGLE); 设置下划线
     * titleRun.setItalic(true); 设置斜体
     * titleRun.setColor("0000FF"); 设置字体颜色
     *
     * @param document 文档对象
     * @param titleStr 标题文本
     * @param titleNo  第几号标题
     * @return 标题段落对象
     */
    public static XWPFParagraph getTitle2Run(XWPFDocument document, String titleStr, int titleNo) {
        int size = TITLE_FONT_SIZES[titleNo - 1];
        // 创建一个段落对象
        XWPFParagraph titleParagraph = document.createParagraph();
        titleParagraph.setStyle("Heading" + titleNo);
        titleParagraph.setSpacingBefore((size << 2) + size);
        titleParagraph.setSpacingAfter(size << 2);
        // 设置段落左对齐
        titleParagraph.setAlignment(ParagraphAlignment.LEFT);

        // 创建一个文本运行对象
        XWPFRun titleRun = titleParagraph.createRun();
        // 设置文本内容
        titleRun.setText(titleStr);
        // 设置字体大小
        titleRun.setFontSize(size);
        // 设置加粗
        titleRun.setBold(true);
        return titleParagraph;
    }

    public static XWPFParagraph getParagraph(XWPFDocument document, String outStr) {
        // 创建一个段落对象
        XWPFParagraph paragraph = document.createParagraph();
        // 行间距
        paragraph.setSpacingBetween(1.2);
        // 首行缩进
        paragraph.setIndentationFirstLine(480);
        // 设置段落对齐方式
        paragraph.setAlignment(ParagraphAlignment.LEFT);

        // 创建一个文本运行对象
        XWPFRun run = paragraph.createRun();
        // 设置文本内容
        run.setText(outStr);
        // 设置字体大小
        run.setFontSize(TEXT_SIZE);

        return paragraph;
    }

    public static void addParagraphs(XWPFDocument document, String outStr) {
        String[] paragraphs = outStr.split("\n");
        for (String text : paragraphs) {
            // 创建一个段落对象
            XWPFParagraph paragraph = document.createParagraph();
            // 行间距
            paragraph.setSpacingBetween(1.1);
            // 设置段落对齐方式
            paragraph.setAlignment(ParagraphAlignment.LEFT);

            // 创建一个文本运行对象
            XWPFRun run = paragraph.createRun();
            // 设置文本内容
            run.setText(text);
            // 设置字体大小
            run.setFontSize(TABLE_SIZE);
        }
    }
}
